package com.fiberhome.opticalbox.ui;

import java.io.File;
import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.fiberhome.opticalbox.R;
import com.fiberhome.airplay.AirPlayClientCallback;
import com.fiberhome.airplay.AirPlayClientService;
import com.fiberhome.opticalbox.App;
import com.fiberhome.opticalbox.BaseActivity;
import com.fiberhome.opticalbox.C;
import com.fiberhome.opticalbox.common.FileSearchService;
import com.fiberhome.opticalbox.ui.fragment.TvProjectionFragment;
import com.fiberhome.opticalbox.utils.AnimUtil;
import com.fiberhome.opticalbox.utils.LogUtil;

/**
 * @author wangpeng
 * 
 */
public class PutVideoActivity extends BaseActivity {
	private int startPosition;

	private AirPlayClientService clientService;

	private File file;

	private CheckBox ckPauseResume;
	private TextView txCurrentProgress, txTotalProgress;
	private SeekBar sbProgress;
	private Dialog dlgNotSupport;

	private TextView txInfo;
	private View layTime;

	private boolean isStart;

	private MediaPlayer mediaPlayer = new MediaPlayer();

	private int currentTime;
	private int totalTime;

	private Handler handler = new Handler();

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.ob_activity_put_video);
		super.onCreate(savedInstanceState);

		startPosition = getIntent().getIntExtra(C.bundle.videoPosition, 0);

		clientService = AirPlayClientService.getInstance();

		titleView.setTitle(R.string.ob_tv_projection);
		titleView.setBackgroundColor(0xff454545);
		titleView.addLeftDrawableMenu(this, R.drawable.ob_ico_back, 15, 25, onBackClickListener);

		txInfo = (TextView) findViewById(R.id.tx_info);

		ckPauseResume = (CheckBox) findViewById(R.id.ck_pause_resume);
		ckPauseResume.setVisibility(View.GONE);
		layTime = findViewById(R.id.lay_time);
		layTime.setVisibility(View.GONE);
		sbProgress = (SeekBar) findViewById(R.id.sb_progress);
		txCurrentProgress = (TextView) findViewById(R.id.tx_current_progress);
		txTotalProgress = (TextView) findViewById(R.id.tx_total_progress);
		ckPauseResume = (CheckBox) findViewById(R.id.ck_pause_resume);
		ckPauseResume.setEnabled(false);
		ckPauseResume.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked && !isStart) {
					ckPauseResume.setVisibility(View.GONE);
					txInfo.setVisibility(View.VISIBLE);
					
					boolean flags = App.getVideoFlags();
					if(true == flags){
						boolean ret = initVideo();
						if(true == ret)
						{
							 App.setVideoFlags(false);
						}
					}
					playVideo();

				} else {
					rateVideo(isChecked);
				}
			}
		});

		sbProgress.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override public void onStopTrackingTouch(SeekBar seekBar) {
				final int currentProgress = seekBar.getProgress();
				txCurrentProgress.setText(formatTime(currentProgress));

				if (currentProgress >= seekBar.getMax()) {
					stopVideo();
				} else {
					seekVideo(currentProgress);
				}
			}

			@Override public void onStartTrackingTouch(SeekBar seekBar) {
				pauseTimeline();
			}

			@Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			}
		});

		clientService.setCallback(callback);
		
		bindFileSearchService();
	}

	private static String formatTime(int time) {
		if (time < 0) {
			return "";
		}
		int s = time % 60;
		int m = (time / 60) % 60;
		int h = time / 3600;

		return (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s;
	}
	private boolean initVideo() {
		LogUtil.i("PutVideoActivity initVideo()");
		try {
			clientService.initVideo(TvProjectionFragment.getSelectedServiceInfo());
			return true ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	private void playVideo() {
		LogUtil.i("PutVideoActivity playVideo()");
		try {
			URL url = new URL("http", TvProjectionFragment.getDeviceAddress(), 9999, file.getAbsolutePath());
			clientService.playVideo(url, TvProjectionFragment.getSelectedServiceInfo());
			isStart = true;
		} catch (Exception e) {
			LogUtil.e("PutVideoActivity playVideo() exception\n" + e.getMessage());
		}
	}
	

	private void stopVideo() {
		LogUtil.i("PutVideoActivity stopVideo()");
		try {
			clientService.stopVideo(TvProjectionFragment.getSelectedServiceInfo());
		} catch (Exception e) {
			LogUtil.e("PutVideoActivity stopVideo() exception\n" + e.getMessage());
		}
	}

	private void rateVideo(boolean is2resume) {
		LogUtil.i("PutVideoActivity rateVideo() is2pause : " + is2resume);
		try {
			clientService.rateVideo(TvProjectionFragment.getSelectedServiceInfo(), is2resume ? "1" : "0");
		} catch (Exception e) {
			LogUtil.e("PutVideoActivity rateVideo() exception\n" + e.getMessage());
		}
	}

	private void seekVideo(float seconds) {
		LogUtil.i("PutVideoActivity seekVideo() seconds : " + seconds);
		try {
			clientService.seekVideo(TvProjectionFragment.getSelectedServiceInfo(), seconds);
		} catch (Exception e) {
			LogUtil.e("PutVideoActivity seekVideo() exception\n" + e.getMessage());
		}
	}

	@Override protected void onDestroy() {
		super.onDestroy();
		unBindFileSearchService();

		stopVideo();

		handler.post(new Runnable() {
			@Override public void run() {
				mediaPlayer.release();
				clientService.shutdown();
			}
		});
	}

	private void bindFileSearchService() {
		Intent intent = new Intent(PutVideoActivity.this, FileSearchService.class);
		bindService(intent, mServiceConnection, Activity.BIND_AUTO_CREATE);
	}

	private void unBindFileSearchService() {
		unbindService(mServiceConnection);
	}

	private final ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override public void onServiceConnected(ComponentName componentName, IBinder service) {
			FileSearchService fileSearchService = ((FileSearchService.LocalBinder) service).getService();
			List<File> fileList = fileSearchService.getVedioList();
			file = fileList.get(startPosition);

			try {
				titleView.setTitle(file.getName());

				mediaPlayer.reset();
				mediaPlayer.setDataSource(file.getAbsolutePath());
				mediaPlayer.prepare();
				currentTime = mediaPlayer.getCurrentPosition() / 1000;
				totalTime = mediaPlayer.getDuration() / 1000;
				LogUtil.i("mediaPlayer file  " + file.getAbsolutePath() + "\nposition:" + currentTime + " total:" + totalTime);

				txCurrentProgress.setText(formatTime(currentTime));
				txTotalProgress.setText(formatTime(totalTime));
				sbProgress.setMax(totalTime);
				sbProgress.setProgress(currentTime);

				ckPauseResume.performClick(); // to start play video
			} catch (Exception e) {

				showToast(R.string.ob_not_support);
				
				sbProgress.setMax(0);
				ckPauseResume.performClick(); // to start play video

				LogUtil.e("PutVideoActivity mediaPlayer setDataSource fail! \nfile:" + file.getAbsolutePath() + "\n" + e.getMessage());
			}
		}

		@Override public void onServiceDisconnected(ComponentName componentName) {
		}
	};

	private Runnable run = new Runnable() {
		@Override public void run() {
			int progress = sbProgress.getProgress();
			if (progress < sbProgress.getMax()) {
				sbProgress.setProgress(progress + 1);
				txCurrentProgress.setText(formatTime(progress + 1));

				handler.postDelayed(run, 1000);
			}else if(sbProgress.getMax() != 0){
				isStart = false;
				pauseTimeline();
				sbProgress.setProgress(0);
				ckPauseResume.setChecked(false);
				txCurrentProgress.setText(R.string.ob_video_zero);
				layTime.startAnimation(AnimUtil.load(PutVideoActivity.this, R.anim.ob_slide_out_bottom));
				layTime.setVisibility(View.GONE);
			}
		}
	};

	private AirPlayClientCallback callback = new AirPlayClientCallback() {
		@Override public void onStopVideoSuccess() {
			handler.post(new Runnable() {
				@Override public void run() {
					isStart = false;
					pauseTimeline();
					sbProgress.setProgress(0);
					ckPauseResume.setChecked(false);
					txCurrentProgress.setText(R.string.ob_video_zero);
					layTime.startAnimation(AnimUtil.load(PutVideoActivity.this, R.anim.ob_slide_out_bottom));
					layTime.setVisibility(View.GONE);
				}
			});
		}

		@Override public void onStopVideoError() {
		}

		@Override public void onSeekVideoSuccess(float seconds) {
			if (ckPauseResume.isChecked()) {
				resumeTimeline();
			}
		}

		@Override public void onSeekVideoError(float seconds) {
		}

		@Override public void onRateVideoSuccess(String state) {
			if (ckPauseResume.isChecked()) {
				resumeTimeline();
			} else {
				pauseTimeline();
			}
		}

		@Override public void onRateVideoError(String state) {
		}

		@Override public void onPlayVideoSuccess(URL location) {
			isStart = true;
			resumeTimeline();

			handler.post(new Runnable() {
				@Override public void run() {
					txInfo.setVisibility(View.GONE);
					ckPauseResume.setVisibility(View.VISIBLE);
					ckPauseResume.startAnimation(AnimUtil.cearteAlpha(0.3f, 1f));
					ckPauseResume.setEnabled(true);

					if(sbProgress.getMax() != 0)
					{
						layTime.setVisibility(View.VISIBLE);
						layTime.startAnimation(AnimUtil.load(PutVideoActivity.this, R.anim.ob_slide_in_bottom));
					}
					else /* 本地解析失败，隐藏进度条 */
					{
						layTime.startAnimation(AnimUtil.load(PutVideoActivity.this, R.anim.ob_slide_out_bottom));
						layTime.setVisibility(View.GONE);
					}
				}
			});
		}

		@Override public void onPlayVideoError(URL location) {
			handler.post(new Runnable() {
				@Override public void run() {
					txInfo.setText(R.string.ob_video_init_fial);
				}
			});
		}

		@Override public void onPutImageSuccess(File file) {
		}

		@Override public void onPutImageError(File file) {
		}

		@Override public void onStopImageSuccess() {
		}

		@Override public void onStopImageError() {
		}
	};

	private void resumeTimeline() {
		pauseTimeline();
		handler.postDelayed(run, 4000);
	}

	private void pauseTimeline() {
		handler.removeCallbacks(run);
	}

	@SuppressWarnings("unused")
	private void showNotSupportDialog() {
		dialogUtil = dialogUtil.createSimple(R.string.ob_not_support, false, true);
		Button btnCancel = dialogUtil.getCancelButton();
		btnCancel.setTextColor(0xffffffff);
		btnCancel.setBackgroundResource(R.drawable.ob_selector_dlg_just_cancel_style_blue);
		dlgNotSupport = dialogUtil.setCancelListener(new OnClickListener() {
			@Override public void onClick(View v) {
				dlgNotSupport.dismiss();
				finish();
			}
		}).show();
	}
	
}